//
//  SendGoodsDatasVC.m
//  NtoccShipper
//
//  Created by mac on 2019/11/20.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "SendGoodsDatasVC.h"
#import "SendGoodsDatasCell.h"
#import "SourceListModel.h"
#import "SourcesOrderVC.h"
#import "SourcesOrderListModel.h"
#import "SourcesOrderListDetailVC.h"
@interface SendGoodsDatasVC ()<UITableViewDelegate,UITableViewDataSource>{
    FlexFrameView *header;
}
@property (nonatomic,strong) SendGoodsDatasCell *sendGoodsDatasCell;
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,strong) CJLabel *labStartTime;
@property (nonatomic,strong) CJLabel *labEndTime;
@property (nonatomic,strong) CJLabel *labSelectType;

@property (nonatomic,copy) NSString *strStartTime;
@property (nonatomic,copy) NSString *strEndTime;
@property (nonatomic,copy) NSString *strSelectType;
@property (nonatomic,strong) NSMutableArray *arrTitles;
@property (nonatomic,strong) NSMutableArray *arrCodes;
@property (nonatomic,strong) CJLabel *labShipper;
@property (nonatomic,strong) UILabel *labGoodsTime;
@end

@implementation SendGoodsDatasVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (self.isSendGoods) {
        [self setTitleName:@"发货统计"];
    }else{
        [self setTitleName:@"收货统计"];
    }
    [self setRightImage:@"重置" image:@""];

    [self setBackLeftButton:@""];
    [self createTopView];
    
    self.sendGoodsDatasCell = [[SendGoodsDatasCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.arrCodes = [[NSMutableArray alloc]init];
    self.arrTitles = [[NSMutableArray alloc]init];
    self.page = 1;
    [self setDefautValue];
}

- (void)setDefautValue{
    self.strStartTime = @"";
    self.strEndTime = @"";
    self.strSelectType = @"";
    self.labStartTime.text = @"开始时间";
    self.labEndTime.text = @"结束时间";
    self.labSelectType.text = @"选择类型";
}

- (void)RightTextClick:(UIButton *)sender{
    [self setDefautValue];
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)createTopView{
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    header = [[FlexFrameView alloc] initWithFlex:@"SendGoodsDatasHeaderView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

    if (self.isSendGoods) {
//        [self setTitleName:@"发货统计"];
        self.labShipper.text = @"发货人";
        self.labGoodsTime.text = @"下单时间";
    }else{
//        [self setTitleName:@"收货统计"];
        self.labShipper.text = @"收货人";
        self.labGoodsTime.text = @"卸货时间";
    }
    
    [header layoutIfNeeded];
    [self.view addSubview:header];
}

- (void)btnSelectStartTimeAction{
   
    [self btnShowDataTimeWithType:@"0"];
}
- (void)btnSelectEndimeAction{
    [self btnShowDataTimeWithType:@"1"];
}

- (void)btnSelectTypeAction{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/goodsType",CJBaseUrl);
    NSDictionary *dicPar = @{
                             @"pageSize":@"1000",
                             @"level":@"4"
    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
//        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        
        if (ws.arrTitles.count > 0) {
            [ws.arrTitles removeAllObjects];
        }
        if (ws.arrCodes.count > 0) {
            [ws.arrCodes removeAllObjects];
        }
        
        [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *dic = (NSDictionary *)obj;
            [ws.arrCodes addObject:dic[@"code"]];
            [ws.arrTitles addObject:dic[@"name"]];
        }];
        [ws selectSamllGoodsTypes:ws.arrTitles codes:ws.arrCodes];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

- (void)selectSamllGoodsTypes:(NSMutableArray *)arrTitle codes:(NSMutableArray *)arrCodes{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = @"类型选择";
    stringPickerView.dataSourceArr = arrTitle;
    WS(ws);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        ws.strSelectType = arrCodes[resultModel.index];
        ws.labSelectType.text = resultModel.selectValue;
        [ws downRefresh];
    };

    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

- (void)btnShowDataTimeWithType:(NSString *)strType{
    
    WS(ws);
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMD];
    datePickerView.title = strType.intValue == 0 ? @"开始时间":@"截止时间";
    datePickerView.minDate = [NSDate br_setYear:2016 month:5 day:1];
    datePickerView.maxDate = [NSDate br_setYear:2050 month:5 day:1];
    datePickerView.resultBlock = ^(NSString *selectValue) {

        if (strType.intValue == 0) {
            ws.labStartTime.text = selectValue;
            ws.strStartTime = CJStringWithFormat(@"%@ 00:00:00",selectValue);
        } else {
            ws.labEndTime.text = selectValue;
            ws.strEndTime = CJStringWithFormat(@"%@ 00:00:00",selectValue);
        }
        [ws downRefresh];
       
    };
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    datePickerView.pickerStyle = customStyle;
    [datePickerView show];
}

/// <#Description#>
- (void)loadData {

    NSString *strURL;
    NSDictionary *dicPar;
    
    if (![CJRegular getIsStrEmpty:self.strEndTime] && ![CJRegular getIsStrEmpty:self.strStartTime]) {
        if ([CJRegular compareDate:self.strStartTime withDate:self.strEndTime]) {
            
        }else{
            [CJAlert showStringDismissWithDelay:@"结束时间必须大于开始时间"];
            return;
        }
    }
    
    if (self.isSendGoods) {
        strURL = CJStringWithFormat(@"%@/ntocc-tms-api/order",CJBaseUrl);
        dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                                 @"pageSize":@"20",
                                 @"startGmtCreated":self.strStartTime, //创建时间 2018-12-29T23:59:59
                                 @"endGmtCreated":self.strEndTime, // 节制时间
                                 @"coalType":self.strSelectType,
                                };
    }else{
        strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail",CJBaseUrl);
        dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                                 @"pageSize":@"20",
                                 @"gmtCreatedStart":self.strStartTime, //创建时间 2018-12-29T23:59:59
                                 @"gmtModifiedEnd":self.strEndTime, // 节制时间
                                 @"coalType":self.strSelectType,
                                };
    }
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

        DLog(@"++++++++%@",responseObject);

        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//        if (list.count > 0) {

            if ([ws.refreshType isEqualToString:@"down"]) {
                [ws.modelArray removeAllObjects];
            }

            NSError * error ;
            
            if (self.isSendGoods) {
                NSArray *arr = [SourceListModel arrayOfModelsFromDictionaries:list error:&error];
                [ws.modelArray addObjectsFromArray:arr];
            }else{
                  NSArray *arr = [SourcesOrderListModel arrayOfModelsFromDictionaries:list error:&error];
                  [ws.modelArray addObjectsFromArray:arr];
                
            }
        
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];

            if (ws.modelArray.count == total.intValue) {
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            
//        }else{
//
//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
    }];

}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"SendGoodsDatasCell";
    SendGoodsDatasCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SendGoodsDatasCell alloc] initWithFlex:nil reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (self.isSendGoods) {
        SourceListModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];

    }else{
        SourcesOrderListModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithConsigneeModel:model];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.isSendGoods) {
        SourceListModel *model = self.modelArray[indexPath.row];
        SourcesOrderVC *vc = [[SourcesOrderVC alloc]init];
        vc.strCode = model.code;
        [self pushVc:vc];
    }else{
        SourcesOrderListModel *model = self.modelArray[indexPath.row];
        SourcesOrderListDetailVC *vc = [[SourcesOrderListDetailVC alloc]init];
        vc.strCode = model.code;
        [self pushVc:vc];
    }
    
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + header.height + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - header.height - CJTableToTopHeight ),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end



